from rest_framework.response import Response
from rest_framework.views import APIView
from apps.UserControl.models.user import *
# from utils.response import ResponsePackaging
from django.conf import settings


class PassWordAPIView(APIView):
    """
    修改密码
    """

    def put(self, request, *args, **kwargs):
        data = request.data
        user_id = data.get('user_id')
        old_password = data.get('old_password')
        password = data.get('password')
        password2 = data.get('password2')
        user = User.objects.get(id=user_id)
        if old_password:
            if password != password2:
                return Response(400, None, "两次密码输入不一致！")

            if len(password) > 20 or len(password) < 6:
                return Response(400, None, "密码长度需要8到20位！")

            if old_password == password:
                return Response(400, None, "新密码与旧密码相同！")

            if user.check_password(old_password):
                user.set_password(password)
                user.save()
                user.password = password
                return Response(200, user.password, "密码修改成功！")

            return Response(400, None, "旧密码校验错误！")

    def post(self, request, *args, **kwargs):
        data = request.data
        user_id = data.get('user_id')
        user = User.objects.get(id=user_id)
        user.set_password(settings.DEFAULT_PASSWD)
        user.save()
        user.password = settings.DEFAULT_PASSWD
        return Response(200, settings.DEFAULT_PASSWD, "密码重置成功,新密码为：" + settings.DEFAULT_PASSWD)
